package com.itheima.health.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Role;
import com.itheima.health.service.RoleService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@RequestMapping("/role")
public class RoleController {

    @Reference
    private RoleService roleService;

    //查询所有角色
    @RequestMapping("findAll")
    public List<Role> findAll() {
        return roleService.findAll();
    }

    //分页查询角色信息
    @RequestMapping("findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return roleService.findPage(queryPageBean);
    }

    //添加角色
    @RequestMapping("add")//注意：@RequestParam("permissionIds/menusIds")可以省略不写，因为参数名都为：userIds/menuIds
    public Result add(@RequestBody Role role, Integer[] permissionIds, Integer[] menuIds) {
        try {
            roleService.add(role, permissionIds, menuIds);
            return new Result(true, MessageConstant.ADD_ROLE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_ROLE_FAIL);
        }
    }

    //根据id查询角色信息，用于表单数据回显
    @RequestMapping("findByRoleId")
    public Role findByRoleId(Integer id) {
        return roleService.findByRoleId(id);
    }

    //根据角色id查询该角色所拥有的所有权限id
    @RequestMapping("findPermissionIdsByRoleId")
    public List<Integer> findPermissionIdsByRoleId(Integer id) {
        return roleService.findPermissionIdsByRoleId(id);
    }

    //根据角色id查询该角色所拥有的所有菜单id
    @RequestMapping("findMenuIdsByRoleId")
    public List<Integer> findMenuIdsByRoleId(Integer id) {
        return roleService.findMenuIdsByRoleId(id);
    }

    //编辑角色
    @RequestMapping("editRole")
    public Result editRole(@RequestBody Role role, Integer[] permissionIds, Integer[] menuIds) {
        try {
            roleService.editRole(role, permissionIds, menuIds);
            return new Result(true, MessageConstant.EDIT_ROLE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_ROLE_FAIL);
        }
    }

    //删除角色信息
    @RequestMapping("deleteRole")
    public Result deleteRole(Integer id) {
        try {
            roleService.deleteRole(id);
            return new Result(true, MessageConstant.DELETE_ROLE_SUCCESS);
        } catch (RuntimeException e) {
            return new Result(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_ROLE_FAIL);
        }
    }
}
